package com.hiultra.archive.service.impl;

import com.hiultra.archive.domain.ArcAccountType;
import com.hiultra.archive.domain.ArcDossier;
import com.hiultra.archive.mapper.ArcAccountTypeMapper;
import com.hiultra.archive.mapper.ArcCatalogMapper;
import com.hiultra.archive.mapper.ArcDossierMapper;
import com.hiultra.archive.service.IArcCatalogService;
import com.hiultra.common.constant.UserConstants;
import com.hiultra.common.core.domain.TreeSelect;
import com.hiultra.common.core.domain.entity.ArcCatalog;
import com.hiultra.common.core.domain.entity.SysDept;
import com.hiultra.common.core.domain.entity.SysUser;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.SecurityUtils;
import com.hiultra.common.utils.StringUtils;
import com.hiultra.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类Service业务层处理
 *
 * @author ls
 * @date 2022-07-28
 */
@Service
public class ArcCatalogServiceImpl implements IArcCatalogService {
    private static final Logger log = LoggerFactory.getLogger(ArcCatalogServiceImpl.class);
    @Autowired
    private ArcCatalogMapper arcCatalogMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ArcDossierMapper arcDossierMapper;
    @Autowired
    private ArcAccountTypeMapper arcAccountTypeMapper;

    /**
     * 查询分类
     *
     * @param catalogId 分类主键
     * @return 分类
     */
    @Override
    public ArcCatalog selectArcCatalogByCatalogId(Long catalogId) {
        return arcCatalogMapper.selectArcCatalogByCatalogId(catalogId);
    }

    /**
     * 查询分类列表
     *
     * @param arcCatalog 分类
     * @return 分类
     */
    @Override
    public List<ArcCatalog> selectArcCatalogList(ArcCatalog arcCatalog) {
        return arcCatalogMapper.selectArcCatalogList(arcCatalog);
    }

    /**
     * 新增分类
     *
     * @param arcCatalog 分类
     * @return 结果
     */
    @Override
    public int insertArcCatalog(ArcCatalog arcCatalog) {
        if (0 != arcCatalog.getParentId()) {
            ArcCatalog info = arcCatalogMapper.selectCatalogById(arcCatalog.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (UserConstants.CATALOG_DISABLE.equals(info.getStatus())) {
                throw new ServiceException("分类停用，无法新增！");
            }
            //查询是否存在重复分类
            ArcCatalog catalog = arcCatalogMapper.selectArcCatalogByCatalogName(arcCatalog.getCatalogName());
            if (StringUtils.isNotNull(catalog)) {
                throw new ServiceException("分类" + arcCatalog.getCatalogName() + "已存在，无法新增！");

            }
            arcCatalog.setAncestors(info.getAncestors() + "," + arcCatalog.getParentId());
        } else {
            arcCatalog.setAncestors("0");
        }
        return arcCatalogMapper.insertArcCatalog(arcCatalog);
    }

    /**
     * 修改分类
     *
     * @param arcCatalog 分类
     * @return 结果
     */
    @Override
    public int updateArcCatalog(ArcCatalog arcCatalog) {
        //查询修改后上级信息
        ArcCatalog newParentCatalog = arcCatalogMapper.selectCatalogById(arcCatalog.getParentId());
        //查询修改前分类信息
        ArcCatalog oldCatalog = arcCatalogMapper.selectCatalogById(arcCatalog.getCatalogId());
        if (StringUtils.isNotNull(newParentCatalog) && StringUtils.isNotNull(oldCatalog)) {
            String newAncestors = newParentCatalog.getAncestors() + "," + newParentCatalog.getCatalogId();
            String oldAncestors = oldCatalog.getAncestors();
            arcCatalog.setAncestors(newAncestors);
            updateCatalogChildren(arcCatalog.getCatalogId(), newAncestors, oldAncestors);
        }

        return arcCatalogMapper.updateArcCatalog(arcCatalog);
    }

    /**
     * 修改子元素关系
     *
     * @param catalogId    被修改的分类ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateCatalogChildren(Long catalogId, String newAncestors, String oldAncestors) {
        List<ArcCatalog> children = arcCatalogMapper.selectChildrenCatalogById(catalogId);
        for (ArcCatalog child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            arcCatalogMapper.updateCatalogChildren(children);
        }
    }

    /**
     * 批量删除分类
     *
     * @param catalogIds 需要删除的分类主键
     * @return 结果
     */
    @Override
    public int deleteArcCatalogByCatalogIds(Long[] catalogIds) {
        return arcCatalogMapper.deleteArcCatalogByCatalogIds(catalogIds);
    }

    /**
     * 删除分类信息
     *
     * @param catalogId 分类主键
     * @return 结果
     */
    @Override
    public int deleteArcCatalogByCatalogId(Long catalogId) {
        return arcCatalogMapper.deleteArcCatalogByCatalogId(catalogId);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param catalogs 部门列表
     * @return 树结构列表
     */
    @Override
    public List<ArcCatalog> buildCatalogTree(List<ArcCatalog> catalogs) {
        List<ArcCatalog> returnList = new ArrayList<ArcCatalog>();
        List<Long> tempList = new ArrayList<Long>();
        for (ArcCatalog catalog : catalogs) {
            tempList.add(catalog.getCatalogId());
        }
        for (ArcCatalog catalog : catalogs) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(catalog.getParentId())) {
                recursionFn(catalogs, catalog);
                returnList.add(catalog);
            }
        }
        if (returnList.isEmpty()) {
            returnList = catalogs;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param catalogs 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildCatalogTreeSelect(List<ArcCatalog> catalogs) {
        List<ArcCatalog> catalogTrees = buildCatalogTree(catalogs);
        return catalogTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ArcCatalog> list, ArcCatalog t) {
        // 得到子节点列表
        List<ArcCatalog> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ArcCatalog tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ArcCatalog> getChildList(List<ArcCatalog> list, ArcCatalog t) {
        List<ArcCatalog> tlist = new ArrayList<ArcCatalog>();
        Iterator<ArcCatalog> it = list.iterator();
        while (it.hasNext()) {
            ArcCatalog n = (ArcCatalog) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCatalogId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ArcCatalog> list, ArcCatalog t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 导入分类数据
     *
     * @param catalogList     分类数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importCatalog(List<ArcCatalog> catalogList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(catalogList) || catalogList.size() == 0) {
            throw new ServiceException("导入分类数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ArcCatalog catalog : catalogList) {

            try {
                ArcAccountType accountType = arcAccountTypeMapper.selectArcAccountTypeByTypeName(catalog.getTypeName());
                ArcCatalog info = arcCatalogMapper.selectArcCatalogByCatalogName(catalog.getParentName());
                if ("顶级".equals(catalog.getParentName())) {
                    catalog.setParentId(0L);
                } else {
                    //根据上级分类名称查询分类对象信息
                    if (StringUtils.isNull(info)) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、分类 " + catalog.getParentName() + ",未查询到上级信息");
                        continue;
                    } else {
                        // 如果父节点不为正常状态,则不允许新增子节点
                        if (UserConstants.CATALOG_DISABLE.equals(info.getStatus())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、分类 " + catalog.getParentName() + ",父节点不为正常状态");
                            continue;
                        }
                        catalog.setParentId(info.getCatalogId());
                        catalog.setAncestors(info.getAncestors() + "," + catalog.getParentId());
                    }
                }
                if (StringUtils.isNull(accountType)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、分类 " + catalog.getParentName() + ",未查询到户号名称");
                    continue;
                } else {
                    catalog.setTypeCode(accountType.getTypeCode());
                }
                // 验证是否存在分类名称
                ArcCatalog c = arcCatalogMapper.selectArcCatalogByCatalogName(catalog.getCatalogName());
                if (StringUtils.isNull(c)) {
                    BeanValidators.validateWithException(validator, catalog);
                    catalog.setCreateBy(operName);
                    this.insertArcCatalog(catalog);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、分类 " + catalog.getCatalogName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, catalog);
                    catalog.setUpdateBy(operName);
                    this.updateArcCatalog(catalog);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "分类 " + catalog.getCatalogName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、分类 " + catalog.getCatalogName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、分类 " + catalog.getCatalogName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
